
import pandas as pd
import mplfinance as mpf
import matplotlib.pyplot as plt

# 读取数据
df = pd.read_excel(r'D:\wordspace\resource\data\原始数据\股票指数\399330_深证100_weekly.xlsx')

df = df.rename(columns={
    '日期': 'Date',
    '开盘': 'Open',
    '收盘': 'Close',
    '最高': 'High',
    '最低': 'Low',
    '成交量': 'Volume'
})
df.set_index('Date', inplace=True)
df.index = pd.to_datetime(df.index)


# 计算MACD指标
exp12 = df['Close'].ewm(span=12, adjust=False).mean()
exp26 = df['Close'].ewm(span=26, adjust=False).mean()
macd = exp12 - exp26
signal = macd.ewm(span=9, adjust=False).mean()
hist = macd - signal

# 创建MACD子图
apds = [
    mpf.make_addplot(macd, panel=1, color='blue', ylabel='MACD'),
    mpf.make_addplot(signal, panel=1, color='orange'),
    mpf.make_addplot(hist, type='bar', panel=1, color='gray')
]

s = mpf.make_mpf_style(
    base_mpf_style='charles',  # 继承基础样式
    rc={'font.family': 'SimHei', 'axes.unicode_minus': False}  # 设置字体为黑体
)

# 绘制K线图
mpf.plot(df, type='candle', style=s,
         mav=(30,),  # 30日均线
         addplot=apds,
         volume=True,
         title='深证100 K线图(30日均线+MACD)',
         ylabel='价格',
         ylabel_lower='MACD',
         figratio=(10, 7),
         figscale=1.2,
         datetime_format='%Y-%m-%d')

plt.show()
